local util = require "util"
local conf = require "conf"
local require = require
local setmetatable = setmetatable
local error = error
local table = table
local ngx = ngx
local string = string
local math = math
local tonumber = tonumber
local tostring = tostring
local os = os
local user = require "user"
package.cpath = "/usr/nginx/?.so;;"
local json = require 'cjson'
module(...)

_VERSION = '0.1'

function default(args)
    if (not args.username and not args.password) and (not args.phone and args.vericode) then
        ngx.print(json.encode({
            err = 1,
            msg = '参数不正确'
        }))
        ngx.exit(200)
    end
    local conf = require "conf"
    local db = conf.get_mysql()
    local res = {}
    if args.username and args.password then
        res = db:query("SELECT *,`user`.id as uid , `user`.name as uname FROM `user` left join `area` on `area`.id = `user`.aid WHERE (username = " .. ngx.quote_sql_str(args.username) .. " OR phone = " .. ngx.quote_sql_str(args.username) .. ") AND pass = " .. ngx.quote_sql_str(args.password))
    elseif args.phone and args.vericode then
        local code = user.checkVerifyCode(args.phone, args.vericode)
        if not code or code ~= args.vericode then
            ngx.print(json.encode({
                err = 1,
                msg = '验证码不对'
            }))
            ngx.exit(200)
        end
        res = db:query("SELECT *,`user`.id as uid,`user`.name as uname FROM `user` left join `area` on `area`.id = `user`.aid WHERE phone = " .. ngx.quote_sql_str(args.phone))
    end
    ngx.log(ngx.ERR, json.encode(res))
    if not res or not res[1] then
        ngx.print(json.encode({
            err = 1,
            msg = '用户名或密码错误'
        }))
        ngx.exit(200)
    elseif res[1].role_id == 3 and not args.fromApp then
        ngx.print(json.encode({
            err = 2,
            msg = '该账号仅限app使用，不允许登录云平台'
        }))
        ngx.exit(200)
    end
    local ipDetails = util.getIpDetails(args.ip)
    ngx.log(ngx.ERR, ipDetails)
    local vals = {}

    vals[#vals + 1] = "login_time = " .. os.time()

    vals[#vals + 1] = "ip_details = '" .. ipDetails .. "'"
    local sql = "UPDATE `user` SET ".. table.concat(vals, ",") .. " WHERE id = " .. res[1].uid
    ngx.log(ngx.ERR, sql)
    local _res = db:query(sql)
    ngx.print(json.encode({
        err = 0,
        token = conf.get_token(res[1].uid, res[1].aid),
        name = res[1].name,
        username = res[1].username,
        uid = res[1].uid,
        uname = res[1].uname,
        role_id = res[1].role_id,
        wind = res[1].wind,
        weather = res[1].weather,
    }))
end

local class_mt = {
    __newindex = function (table, key, val)
        error('attempt to write to undeclared variable "' .. key .. '"')
    end
}
setmetatable(_M, class_mt)